<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF页码拆分工具</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="../../assets/js/tailwind.min.js"></script>
    <!-- 本地引用pdf-lib.min.js，FileSaver.min.js -->
    <script src="../../assets/js/pdf-lib.min.js"></script>
    <script src="../../assets/js/FileSaver.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#6366F1',
                        neutral: '#1F2937',
                        'neutral-light': '#F3F4F6'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-height {
                transition: max-height 0.3s ease-in-out;
            }
            .drop-shadow-lg {
                filter: drop-shadow(0 10px 8px rgb(0 0 0 / 0.04)) drop-shadow(0 4px 3px rgb(0 0 0 / 0.1));
            }
            .bg-gradient-primary {
                background: linear-gradient(135deg, #3B82F6 0%, #6366F1 100%);
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-neutral min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-md sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <!-- 替换为emoji -->
                <span class="text-primary text-2xl">✂️</span>
                <h1 class="text-xl font-bold text-neutral">PDF页码拆分工具</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="theme-toggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <span class="text-neutral">🌙</span>
                </button>
                <button id="help-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <span class="text-neutral">❓</span>
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 功能区 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 左侧：文件上传和页码输入 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-6 h-full flex flex-col">
                    <h3 class="text-xl font-bold text-neutral mb-4 flex items-center">
                        <!-- 替换为emoji -->
                        <span class="text-primary mr-2">⬆️</span>上传PDF文件
                    </h3>
                    
                    <!-- 文件上传区域 -->
                    <div id="drop-area" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center mb-6 cursor-pointer hover:border-primary transition-colors">
                        <!-- 替换为emoji -->
                        <span class="text-5xl text-gray-400 mb-4">📄</span>
                        <p class="text-gray-500 mb-2">拖放PDF文件到此处，或</p>
                        <button id="select-file-btn" class="bg-primary hover:bg-primary/90 text-white py-2 px-4 rounded-lg transition-colors">
                            <!-- 替换为emoji -->
                            <span class="mr-2">📁</span>选择文件
                        </button>
                        <input type="file" id="file-input" accept=".pdf" class="hidden">
                        <p id="file-name" class="mt-4 text-sm text-gray-600 truncate"></p>
                    </div>

                    <!-- 页码输入区域 -->
                    <div class="mb-6">
                        <label for="page-ranges" class="block text-sm font-medium text-gray-700 mb-1">页码范围</label>
                        <div class="relative">
                            <input type="text" id="page-ranges" placeholder="例如：1-3,7,9" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all">
                            <div class="absolute right-3 top-2.5 text-gray-400">
                                <!-- 替换为emoji -->
                                <span>✏️</span>
                            </div>
                        </div>
                        <p class="mt-1 text-xs text-gray-500">输入需要提取的页码或范围，用逗号分隔</p>
                    </div>

                    <!-- 拆分模式选择 -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">拆分模式</label>
                        <div class="space-y-3">
                            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="radio" name="split-mode" value="single" class="mr-3 h-4 w-4 text-primary focus:ring-primary">
                                <span>提取到单个PDF</span>
                            </label>
                            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="radio" name="split-mode" value="multiple" checked class="mr-3 h-4 w-4 text-primary focus:ring-primary">
                                <span>每个范围单独生成PDF</span>
                            </label>
                        </div>
                    </div>

                    <!-- 处理按钮 -->
                    <button id="process-btn" class="mt-auto bg-gradient-primary hover:opacity-95 text-white py-3 px-6 rounded-lg font-medium transition-all transform hover:translate-y-[-2px] hover:shadow-lg flex items-center justify-center">
                        <!-- 替换为emoji -->
                        <span class="mr-2">✂️</span>
                        <span>开始拆分PDF</span>
                    </button>
                </div>
            </div>

            <!-- 右侧：处理结果 -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-6 h-full flex flex-col">
                    <h3 class="text-xl font-bold text-neutral mb-4 flex items-center">
                        <!-- 替换为emoji -->
                        <span class="text-primary mr-2">⚙️</span>处理结果
                    </h3>
                    
                    <!-- 处理状态 -->
                    <div id="status-container" class="mb-6 bg-gray-50 rounded-lg p-4 border border-gray-200 flex-grow">
                        <div id="status-placeholder" class="text-center py-10">
                            <!-- 替换为emoji -->
                            <span class="text-4xl text-gray-300 mb-3">📑</span>
                            <p class="text-gray-500">请上传PDF文件并设置页码范围后开始处理</p>
                        </div>
                        <div id="processing-status" class="hidden">
                            <div class="flex items-center mb-3">
                                <!-- 替换为emoji -->
                                <span class="mr-3">⌛</span>
                                <span class="font-medium">正在处理...</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2.5">
                                <div id="progress-bar" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                            </div>
                            <p id="progress-text" class="mt-2 text-sm text-gray-600">准备中...</p>
                        </div>
                        <div id="result-container" class="hidden">
                            <div class="flex justify-between items-center mb-3">
                                <h4 class="font-medium text-gray-800">处理完成!</h4>
                                <button id="download-all-btn" class="bg-secondary hover:bg-secondary/90 text-white py-1 px-3 rounded-lg text-sm transition-colors flex items-center">
                                    <!-- 替换为emoji -->
                                    <span class="mr-1">📥</span> 一键下载全部
                                </button>
                            </div>
                            <div id="result-files" class="space-y-3"></div>
                        </div>
                        <div id="error-container" class="hidden">
                            <div class="bg-red-50 border border-red-400 text-red-700 px-4 py-3 rounded-lg relative">
                                <!-- 替换为emoji -->
                                <strong class="font-bold">❌</strong>
                                <span id="error-message" class="block sm:inline ml-2"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 帮助模态框 -->
    <div id="help-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-xl font-bold text-neutral">使用帮助</h3>
                <button id="close-help" class="text-gray-400 hover:text-gray-600">
                    <!-- 替换为emoji -->
                    <span class="text-xl">❌</span>
                </button>
            </div>
            <div class="p-6 space-y-4">
                <div>
                    <h4 class="font-bold text-gray-800 mb-2">如何使用PDF拆分工具？</h4>
                    <ol class="list-decimal pl-5 space-y-2 text-gray-700">
                        <li>点击"选择文件"按钮或拖放PDF文件到上传区域</li>
                        <li>在"页码范围"输入框中指定需要提取的页码，例如："1-3,7,9"</li>
                        <li>选择拆分模式：提取到单个PDF或每个范围单独生成PDF</li>
                        <li>点击"开始拆分PDF"按钮开始处理</li>
                        <li>处理完成后，下载生成的PDF文件</li>
                    </ol>
                </div>
                <div>
                    <h4 class="font-bold text-gray-800 mb-2">页码格式说明</h4>
                    <ul class="list-disc pl-5 space-y-2 text-gray-700">
                        <li>单个页码：直接输入页码，如"1"</li>
                        <li>连续页码：使用短横线连接起始和结束页码，如"1-5"</li>
                        <li>多个页码或范围：请使用逗号分隔，如"1-3,7,9-12"</li>
                        <li>页码范围必须从小到大排列，如"3-5"是有效的，但"5-3"是无效的</li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-bold text-gray-800 mb-2">注意事项</h4>
                    <ul class="list-disc pl-5 space-y-2 text-gray-700">
                        <li>工具在浏览器中处理PDF，不会上传您的文件到服务器</li>
                        <li>大型PDF文件可能需要更长的处理时间</li>
                        <li>确保输入的页码在PDF有效范围内</li>
                        <li>生成的PDF文件可能会比原文件小，具体取决于提取的页数</li>
                    </ul>
                </div>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end">
                <button id="close-help-btn" class="bg-primary hover:bg-primary/90 text-white py-2 px-4 rounded-lg transition-colors">
                    我知道了
                </button>
            </div>
        </div>
    </div>

    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const dropArea = document.getElementById('drop-area');
            const fileInput = document.getElementById('file-input');
            const selectFileBtn = document.getElementById('select-file-btn');
            const fileName = document.getElementById('file-name');
            const pageRangesInput = document.getElementById('page-ranges');
            const processBtn = document.getElementById('process-btn');
            const statusPlaceholder = document.getElementById('status-placeholder');
            const processingStatus = document.getElementById('processing-status');
            const resultContainer = document.getElementById('result-container');
            const resultFiles = document.getElementById('result-files');
            const errorContainer = document.getElementById('error-container');
            const errorMessage = document.getElementById('error-message');
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            const helpBtn = document.getElementById('help-btn');
            const helpModal = document.getElementById('help-modal');
            const closeHelp = document.getElementById('close-help');
            const closeHelpBtn = document.getElementById('close-help-btn');
            const themeToggle = document.getElementById('theme-toggle');
            const downloadAllBtn = document.getElementById('download-all-btn');
            
            // 全局变量
            let selectedFile = null;
            let isDarkMode = false;
            let downloadLinks = [];
            
            // 文件选择按钮点击事件
            selectFileBtn.addEventListener('click', () => {
                fileInput.click();
            });
            
            // 文件选择变化事件
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFileSelection(e.target.files[0]);
                }
            });
            
            // 拖放相关事件
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            ['dragenter', 'dragover'].forEach(eventName => {
                dropArea.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, unhighlight, false);
            });
            
            function highlight() {
                dropArea.classList.add('border-primary', 'bg-blue-50');
            }
            
            function unhighlight() {
                dropArea.classList.remove('border-primary', 'bg-blue-50');
            }
            
            dropArea.addEventListener('drop', handleDrop, false);
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const file = dt.files[0];
                
                if (file) {
                    handleFileSelection(file);
                }
            }
            
            // 处理文件选择
            function handleFileSelection(file) {
                if (file.type !== 'application/pdf') {
                    showError('请选择PDF文件');
                    return;
                }
                
                selectedFile = file;
                fileName.textContent = file.name;
                fileName.classList.remove('hidden');
                
                // 显示文件图标和基本信息
                dropArea.innerHTML = `
                    <div class="flex items-center justify-center space-x-4">
                        <!-- 替换为emoji -->
                        <span class="text-4xl text-red-500">📄</span>
                        <div class="text-left">
                            <p class="font-medium">${file.name}</p>
                            <p class="text-sm text-gray-500">${formatFileSize(file.size)}</p>
                        </div>
                    </div>
                `;
                
                // 重置状态
                resetStatus();
            }
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // 处理按钮点击事件
            processBtn.addEventListener('click', async () => {
                if (!selectedFile) {
                    showError('请先选择PDF文件');
                    return;
                }
                
                const pageRanges = pageRangesInput.value.trim();
                if (!pageRanges) {
                    showError('请输入页码范围');
                    return;
                }
                
                try {
                    // 解析页码范围
                    const pageNumbers = parsePageRanges(pageRanges);
                    
                    if (pageNumbers.length === 0) {
                        showError('无效的页码范围');
                        return;
                    }
                    
                    // 显示处理状态
                    showProcessing();
                    
                    // 清空下载链接数组
                    downloadLinks = [];
                    
                    // 处理PDF
                    await processPDF(selectedFile, pageNumbers);
                    
                } catch (error) {
                    showError(error.message || '处理PDF时出错');
                    console.error(error);
                }
            });
            
            // 解析页码范围 - 支持中英文逗号
            function parsePageRanges(input) {
                // 替换中文逗号为英文逗号
                const normalizedInput = input.replace(/，/g, ',');
                
                const pageNumbers = new Set();
                const ranges = normalizedInput.split(',').map(range => range.trim());
                
                for (const range of ranges) {
                    if (range.includes('-')) {
                        // 处理范围，如"1-3"
                        const [start, end] = range.split('-').map(num => parseInt(num.trim(), 10));
                        
                        if (isNaN(start) || isNaN(end) || start <= 0 || end < start) {
                            throw new Error(`无效的页码范围: ${range}`);
                        }
                        
                        for (let i = start; i <= end; i++) {
                            pageNumbers.add(i);
                        }
                    } else {
                        // 处理单个页码，如"5"
                        const page = parseInt(range, 10);
                        
                        if (isNaN(page) || page <= 0) {
                            throw new Error(`无效的页码: ${range}`);
                        }
                        
                        pageNumbers.add(page);
                    }
                }
                
                // 转换为排序后的数组
                return Array.from(pageNumbers).sort((a, b) => a - b);
            }
            
            // 处理PDF
            async function processPDF(file, pageNumbers) {
                try {
                    // 读取PDF文件
                    const arrayBuffer = await readFileAsArrayBuffer(file);
                    
                    // 加载PDF文档
                    const { PDFDocument, StandardFonts } = PDFLib;
                    const pdfDoc = await PDFDocument.load(arrayBuffer);
                    
                    // 检查页码是否超出范围
                    const totalPages = pdfDoc.getPageCount();
                    const invalidPages = pageNumbers.filter(page => page > totalPages);
                    
                    if (invalidPages.length > 0) {
                        throw new Error(`页码超出范围: ${invalidPages.join(', ')} (总页数: ${totalPages})`);
                    }
                    
                    // 获取拆分模式
                    const splitMode = document.querySelector('input[name="split-mode"]:checked').value;
                    
                    if (splitMode === 'single') {
                        // 提取到单个PDF
                        await extractToSinglePDF(pdfDoc, pageNumbers, file.name);
                    } else {
                        // 每个范围单独生成PDF
                        await splitToMultiplePDFs(pdfDoc, pageNumbers, file.name);
                    }
                    
                } catch (error) {
                    throw error;
                }
            }
            
            // 读取文件为ArrayBuffer
            function readFileAsArrayBuffer(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = () => reject(reader.error);
                    
                    reader.readAsArrayBuffer(file);
                });
            }
            
            // 提取到单个PDF
            async function extractToSinglePDF(pdfDoc, pageNumbers, originalFileName) {
                try {
                    // 创建新的PDF文档
                    const { PDFDocument } = PDFLib;
                    const newPdfDoc = await PDFDocument.create();
                    
                    // 复制选定的页面
                    updateProgress(10, '正在复制页面...');
                    const pagesToCopy = await newPdfDoc.copyPages(pdfDoc, pageNumbers.map(num => num - 1));
                    
                    updateProgress(50, '正在添加页面...');
                    for (const page of pagesToCopy) {
                        newPdfDoc.addPage(page);
                    }
                    
                    // 保存PDF
                    updateProgress(80, '正在保存PDF...');
                    const pdfBytes = await newPdfDoc.save();
                    
                    updateProgress(100, '处理完成!');
                    
                    // 创建下载链接
                    const fileName = getOutputFileName(originalFileName, pageNumbers);
                    createDownloadLink(pdfBytes, fileName, [pageNumbers]);
                    
                } catch (error) {
                    throw error;
                }
            }
            
            // 每个范围单独生成PDF
            async function splitToMultiplePDFs(pdfDoc, pageNumbers, originalFileName) {
                try {
                    const { PDFDocument } = PDFLib;
                    
                    // 将连续的页码分组
                    const pageGroups = groupConsecutiveNumbers(pageNumbers);
                    const totalGroups = pageGroups.length;
                    const results = [];
                    
                    for (let i = 0; i < totalGroups; i++) {
                        const group = pageGroups[i];
                        
                        // 更新进度
                        const progress = Math.floor((i / totalGroups) * 80);
                        updateProgress(progress, `正在处理范围 ${i+1}/${totalGroups}: ${formatPageRange(group)}`);
                        
                        // 创建新的PDF文档
                        const newPdfDoc = await PDFDocument.create();
                        
                        // 复制选定的页面
                        const pagesToCopy = await newPdfDoc.copyPages(pdfDoc, group.map(num => num - 1));
                        
                        for (const page of pagesToCopy) {
                            newPdfDoc.addPage(page);
                        }
                        
                        // 保存PDF
                        const pdfBytes = await newPdfDoc.save();
                        
                        // 生成文件名
                        const fileName = getOutputFileName(originalFileName, group, i + 1);
                        results.push({ bytes: pdfBytes, fileName: fileName, pages: group });
                    }
                    
                    updateProgress(100, '处理完成!');
                    
                    // 创建所有下载链接
                    createDownloadLink(results.map(r => r.bytes), results.map(r => r.fileName), pageGroups);
                    
                } catch (error) {
                    throw error;
                }
            }
            
            // 分组连续的数字
            function groupConsecutiveNumbers(numbers) {
                if (numbers.length === 0) return [];
                
                const groups = [[numbers[0]]];
                let currentGroup = groups[0];
                
                for (let i = 1; i < numbers.length; i++) {
                    if (numbers[i] === numbers[i - 1] + 1) {
                        currentGroup.push(numbers[i]);
                    } else {
                        currentGroup = [numbers[i]];
                        groups.push(currentGroup);
                    }
                }
                
                return groups;
            }
            
            // 格式化页码范围显示
            function formatPageRange(pages) {
                if (pages.length === 1) {
                    return `第 ${pages[0]} 页`;
                } else if (pages.length === 2 && pages[1] === pages[0] + 1) {
                    return `第 ${pages[0]} 和 ${pages[1]} 页`;
                } else {
                    return `第 ${pages[0]}-${pages[pages.length - 1]} 页`;
                }
            }
            
            // 生成输出文件名
            function getOutputFileName(originalFileName, pages, partNumber = null) {
                // 移除文件扩展名
                const nameWithoutExt = originalFileName.replace(/\.pdf$/i, '');
                
                // 生成页码部分
                let pagePart;
                if (pages.length === 1) {
                    pagePart = `_第${pages[0]}页`;
                } else if (pages.length === 2 && pages[1] === pages[0] + 1) {
                    pagePart = `_第${pages[0]}和${pages[1]}页`;
                } else {
                    pagePart = `_第${pages[0]}-${pages[pages.length - 1]}页`;
                }
                
                // 添加部分编号（如果有）
                const partPart = partNumber ? `_部分${partNumber}` : '';
                
                return `${nameWithoutExt}${partPart}${pagePart}.pdf`;
            }
            
            // 创建下载链接
            function createDownloadLink(pdfBytes, fileName, pageGroups) {
                // 隐藏处理状态，显示结果
                processingStatus.classList.add('hidden');
                resultContainer.classList.remove('hidden');
                
                // 清空结果容器
                resultFiles.innerHTML = '';
                
                // 如果是单个PDF
                if (!Array.isArray(pdfBytes)) {
                    const fileUrl = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf' }));
                    
                    // 保存下载链接
                    downloadLinks.push({ url: fileUrl, name: fileName });
                    
                    const fileItem = document.createElement('div');
                    fileItem.className = 'bg-gray-50 p-3 rounded-lg border border-gray-200 flex items-center justify-between';
                    fileItem.innerHTML = `
                        <div class="flex items-center">
                            <!-- 替换为emoji -->
                            <span class="text-red-500 mr-3">📄</span>
                            <div>
                                <p class="font-medium truncate max-w-[300px]">${fileName}</p>
                                <p class="text-xs text-gray-500">${formatPageRange(pageGroups[0])}</p>
                            </div>
                        </div>
                        <div class="flex space-x-2">
                            <a href="${fileUrl}" download="${fileName}" class="bg-primary hover:bg-primary/90 text-white py-1 px-3 rounded-lg text-sm transition-colors flex items-center download-link">
                                <!-- 替换为emoji -->
                                <span class="mr-1">📥</span> 下载
                            </a>
                        </div>
                    `;
                    
                    resultFiles.appendChild(fileItem);
                    
                } else {
                    // 多个PDF
                    for (let i = 0; i < pdfBytes.length; i++) {
                        const fileUrl = URL.createObjectURL(new Blob([pdfBytes[i]], { type: 'application/pdf' }));
                        
                        // 保存下载链接
                        downloadLinks.push({ url: fileUrl, name: fileName[i] });
                        
                        const fileItem = document.createElement('div');
                        fileItem.className = 'bg-gray-50 p-3 rounded-lg border border-gray-200 flex items-center justify-between';
                        fileItem.innerHTML = `
                            <div class="flex items-center">
                                <!-- 替换为emoji -->
                                <span class="text-red-500 mr-3">📄</span>
                                <div>
                                    <p class="font-medium truncate max-w-[300px]">${fileName[i]}</p>
                                    <p class="text-xs text-gray-500">${formatPageRange(pageGroups[i])}</p>
                                </div>
                            </div>
                            <div class="flex space-x-2">
                                <a href="${fileUrl}" download="${fileName[i]}" class="bg-primary hover:bg-primary/90 text-white py-1 px-3 rounded-lg text-sm transition-colors flex items-center download-link">
                                    <!-- 替换为emoji -->
                                    <span class="mr-1">📥</span> 下载
                                </a>
                            </div>
                        `;
                        
                        resultFiles.appendChild(fileItem);
                    }
                }
                
                // 添加一键下载全部按钮事件
                downloadAllBtn.addEventListener('click', downloadAllFiles);
            }
            
            // 一键下载所有文件
            function downloadAllFiles() {
                // 检查是否有文件可下载
                if (downloadLinks.length === 0) {
                    showError('没有文件可下载');
                    return;
                }
                
                // 逐个下载文件
                downloadLinks.forEach((link, index) => {
                    setTimeout(() => {
                        const a = document.createElement('a');
                        a.href = link.url;
                        a.download = link.name;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }, index * 500); // 每个下载之间添加延迟，避免浏览器阻塞
                });
            }
            
            // 更新进度
            function updateProgress(percentage, text) {
                progressBar.style.width = `${percentage}%`;
                progressText.textContent = text;
            }
            
            // 显示处理状态
            function showProcessing() {
                statusPlaceholder.classList.add('hidden');
                errorContainer.classList.add('hidden');
                resultContainer.classList.add('hidden');
                processingStatus.classList.remove('hidden');
                
                updateProgress(0, '开始处理...');
            }
            
            // 显示错误
            function showError(message) {
                statusPlaceholder.classList.add('hidden');
                processingStatus.classList.add('hidden');
                resultContainer.classList.add('hidden');
                errorContainer.classList.remove('hidden');
                
                errorMessage.textContent = message;
            }
            
            // 重置状态
            function resetStatus() {
                statusPlaceholder.classList.remove('hidden');
                processingStatus.classList.add('hidden');
                resultContainer.classList.add('hidden');
                errorContainer.classList.add('hidden');
            }
            
            // 帮助模态框事件
            helpBtn.addEventListener('click', () => {
                helpModal.classList.remove('hidden');
            });
            
            closeHelp.addEventListener('click', () => {
                helpModal.classList.add('hidden');
            });
            
            closeHelpBtn.addEventListener('click', () => {
                helpModal.classList.add('hidden');
            });
            
            // 点击模态框外部关闭
            helpModal.addEventListener('click', (e) => {
                if (e.target === helpModal) {
                    helpModal.classList.add('hidden');
                }
            });
            
            // 主题切换
            themeToggle.addEventListener('click', () => {
                isDarkMode = !isDarkMode;
                
                if (isDarkMode) {
                    document.body.classList.add('bg-gray-900', 'text-white');
                    document.body.classList.remove('bg-gray-50', 'text-neutral');
                    // 替换为emoji
                    themeToggle.innerHTML = '<span class="text-yellow-400">☀️</span>';
                } else {
                    document.body.classList.remove('bg-gray-900', 'text-white');
                    document.body.classList.add('bg-gray-50', 'text-neutral');
                    // 替换为emoji
                    themeToggle.innerHTML = '<span class="text-neutral">🌙</span>';
                }
            });
        });
    </script>
</body>
</html>
    